package top.zhenganwen.securitydemo.web.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author zhenganwen
 * @date 2019/8/20
 * @desc TimeFilter
 */
//@Component
public class TimeFilter implements Filter {

    // 在web容器启动时执行
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("TimeFilter init");
    }

    // 在收到请求时执行，这时请求还未到达SpringMVC的入口DispatcherServlet
    // 单次请求只会执行一次（不论期间发生了几次请求转发）
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException,
            ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        String service = "【" + request.getMethod() + " " + request.getRequestURI() + "】";
        System.out.println("[TimeFilter] 收到服务调用：" + service);

        Date start = new Date();
        System.out.println("[TimeFilter] 开始执行服务" + service + simpleDateFormat.format(start));

        filterChain.doFilter(servletRequest, servletResponse);

        Date end = new Date();
        System.out.println("[TimeFilter] 服务" + service + "执行完毕 " + simpleDateFormat.format(end) +
                "，共耗时：" + (end.getTime() - start.getTime()) + "ms");
    }

    // 在容器销毁时执行
    @Override
    public void destroy() {
        System.out.println("TimeFilter destroyed");
    }
}
